#include "mq_connection.hpp"


void cb(mymq::Channel::ptr& channel, const std::string& ctag, const mymq::BasicProperties* bp, const std::string& body)
{
    // 处理接收到的消息
    std::cout << "消费者 " << ctag << " 消费了消息：" << body << std::endl;
    // 手动确认
    channel->basicAck(bp->id());
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        // 消费者需要指定 要订阅的队列
        std::cout << "usage: ./client queue_name" << std::endl;
        return -1;
    }
    // 1.实例化异步工作对象
    mymq::Async::ptr async_worker = std::make_shared<mymq::Async>();
    // 2.实例化连接对象
    mymq::Connection::ptr conn = std::make_shared<mymq::Connection>("127.0.0.1", 8085, async_worker);
    // 3.通过连接，实例化信道
    mymq::Channel::ptr channel = conn->openChannel();
    // 4.通过信道提供的服务，完成需求
    //  1.声明交换机，类型为广播
    google::protobuf::Map<std::string, std::string> emp_args;
    channel->declareExchange("exchange1", mymq::ExchangeType::TOPIC, true, false, emp_args);
    //  2.声明队列 queue1
    channel->declareQueue("queue1", true, false, false, emp_args);
    //  3.声明队列 queue2
    channel->declareQueue("queue2", true, false, false, emp_args);
    //  4.绑定队列1，bingingkey 设置为 queue1
    channel->queueBind("exchange1", "queue1", "queue1");
    //  5.绑定队列2，bingingkey 设置为 news.music.#
    channel->queueBind("exchange1", "queue2", "news.music.#");

    // 6.消费者订阅队列
    auto functor = std::bind(cb, channel, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
    channel->basicConsume("consumer1", argv[1], false, functor);

    while(1) std::this_thread::sleep_for(std::chrono::seconds(3));
    conn->closeChannel(channel);
    return 0;
}